<template>
  <div class="love-app">
    <!-- 头部 -->
    <div class="chat-header">
      <button @click="goBack" class="back-button">
        ← 返回
      </button>
      <div class="header-info">
        <h2 class="app-title">💕 AI 恋爱大师</h2>
        <p class="app-subtitle">专业的情感咨询助手</p>
      </div>
      <div class="header-actions">
        <button @click="clearChat" class="clear-button">
          清空对话
        </button>
      </div>
    </div>

    <!-- 聊天区域 -->
    <div class="chat-container">
      <div class="chat-messages" ref="messagesContainer">
        <div v-if="messages.length === 0" class="welcome-message">
          <div class="welcome-icon">💕</div>
          <h3>欢迎使用 AI 恋爱大师</h3>
          <p>我是您的专业情感咨询师，可以帮助您解决恋爱中的各种问题。</p>
          <div class="suggestion-buttons">
            <button @click="sendSuggestion" class="suggestion-btn">如何开始一段新恋情？</button>
            <button @click="sendSuggestion" class="suggestion-btn">怎样维持长期关系？</button>
            <button @click="sendSuggestion" class="suggestion-btn">如何处理感情矛盾？</button>
          </div>
        </div>
        
        <ChatMessage
          v-for="message in messages"
          :key="message.id"
          :content="message.content"
          :isUser="message.isUser"
          :timestamp="message.timestamp"
        />
        
        <!-- AI 正在输入指示器 -->
        <div v-if="isAiTyping" class="typing-indicator">
          <div class="typing-avatar">
            <div class="avatar">🤖</div>
          </div>
          <div class="typing-content">
            <div class="typing-bubble">
              <div class="typing-dots">
                <span></span>
                <span></span>
                <span></span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 输入区域 -->
    <ChatInput
      :placeholder="'请向恋爱大师咨询情感问题...'"
      :disabled="isLoading"
      @send="sendMessage"
    />
  </div>
</template>

<script>
import ChatMessage from '../components/ChatMessage.vue'
import ChatInput from '../components/ChatInput.vue'
import { SSEClient, generateChatId } from '../utils/sse.js'

export default {
  name: 'LoveApp',
  components: {
    ChatMessage,
    ChatInput
  },
  data() {
    return {
      messages: [],
      isLoading: false,
      isAiTyping: false,
      chatId: '',
      sseClient: null,
      currentAiMessage: '' // 用于累积AI的流式回复
    }
  },
  created() {
    this.chatId = generateChatId()
    this.sseClient = new SSEClient()
    console.log('生成聊天室ID:', this.chatId)
  },
  beforeUnmount() {
    // 组件销毁时关闭SSE连接
    if (this.sseClient) {
      this.sseClient.close()
    }
  },
  methods: {
    goBack() {
      this.$router.push('/')
    },
    
    clearChat() {
      this.messages = []
      this.chatId = generateChatId()
      console.log('清空对话，生成新的聊天室ID:', this.chatId)
    },
    
    sendSuggestion(event) {
      const suggestion = event.target.textContent
      this.sendMessage(suggestion)
    },
    
    sendMessage(message) {
      if (!message.trim() || this.isLoading) return

      // 添加用户消息
      const userMessage = {
        id: Date.now(),
        content: message,
        isUser: true,
        timestamp: new Date()
      }
      this.messages.push(userMessage)
      
      // 设置加载状态
      this.isLoading = true
      this.isAiTyping = true
      this.currentAiMessage = ''
      
      // 滚动到底部
      this.$nextTick(() => {
        this.scrollToBottom()
      })

      // 建立SSE连接
      this.sseClient.connectLoveApp(
        message,
        this.chatId,
        this.onSSEMessage,
        this.onSSEError,
        this.onSSEComplete
      )
    },
    
    onSSEMessage(data) {
      // 累积AI的流式回应
      this.currentAiMessage += data
      
      // 查找最后一条AI消息并更新，如果没有则创建新的
      const lastMessage = this.messages[this.messages.length - 1]
      if (lastMessage && !lastMessage.isUser && lastMessage.isStreaming) {
        lastMessage.content = this.currentAiMessage
      } else {
        // 创建新的AI消息
        const aiMessage = {
          id: Date.now() + 1,
          content: this.currentAiMessage,
          isUser: false,
          timestamp: new Date(),
          isStreaming: true
        }
        this.messages.push(aiMessage)
        this.isAiTyping = false // 开始显示内容后隐藏"正在输入"
      }
      
      this.$nextTick(() => {
        this.scrollToBottom()
      })
    },
    
    onSSEError(error) {
      console.error('SSE连接错误:', error)
      this.isLoading = false
      this.isAiTyping = false
      
      // 添加错误消息
      const errorMessage = {
        id: Date.now() + 1,
        content: '抱歉，连接出现问题，请稍后重试。',
        isUser: false,
        timestamp: new Date()
      }
      this.messages.push(errorMessage)
    },
    
    onSSEComplete() {
      console.log('SSE连接完成')
      this.isLoading = false
      this.isAiTyping = false
      
      // 标记最后一条AI消息为完成状态
      const lastMessage = this.messages[this.messages.length - 1]
      if (lastMessage && !lastMessage.isUser) {
        lastMessage.isStreaming = false
      }
    },
    
    scrollToBottom() {
      const container = this.$refs.messagesContainer
      if (container) {
        container.scrollTop = container.scrollHeight
      }
    }
  }
}
</script>

<style scoped>
.love-app {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: linear-gradient(135deg, #ff9a9e 0%, #fecfef 50%, #fecfef 100%);
}

.chat-header {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  padding: 16px 24px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-bottom: 1px solid rgba(255, 255, 255, 0.2);
  box-shadow: 0 2px 20px rgba(0, 0, 0, 0.1);
}

.back-button, .clear-button {
  background: rgba(255, 255, 255, 0.8);
  color: #495057;
  border: 1px solid rgba(0, 0, 0, 0.1);
  padding: 8px 16px;
  border-radius: 20px;
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 14px;
}

.back-button:hover, .clear-button:hover {
  background: white;
  transform: translateY(-1px);
}

.header-info {
  text-align: center;
  flex: 1;
}

.app-title {
  font-size: 1.5rem;
  font-weight: 600;
  color: #2c3e50;
  margin: 0;
}

.app-subtitle {
  color: #6c757d;
  margin: 4px 0 0 0;
  font-size: 0.9rem;
}

.chat-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  background: rgba(255, 255, 255, 0.1);
}

.welcome-message {
  text-align: center;
  padding: 40px 20px;
  color: white;
}

.welcome-icon {
  font-size: 4rem;
  margin-bottom: 20px;
}

.welcome-message h3 {
  font-size: 1.8rem;
  margin-bottom: 12px;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
}

.welcome-message p {
  font-size: 1.1rem;
  margin-bottom: 30px;
  opacity: 0.9;
}

.suggestion-buttons {
  display: flex;
  flex-direction: column;
  gap: 12px;
  max-width: 400px;
  margin: 0 auto;
}

.suggestion-btn {
  background: rgba(255, 255, 255, 0.2);
  color: white;
  border: 1px solid rgba(255, 255, 255, 0.3);
  padding: 12px 20px;
  border-radius: 25px;
  cursor: pointer;
  transition: all 0.3s ease;
  backdrop-filter: blur(10px);
}

.suggestion-btn:hover {
  background: rgba(255, 255, 255, 0.3);
  transform: translateY(-2px);
}

.typing-indicator {
  display: flex;
  margin-bottom: 20px;
}

.typing-avatar {
  flex-shrink: 0;
  margin: 0 12px;
}

.typing-avatar .avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
  background: linear-gradient(45deg, #667eea, #764ba2);
  color: white;
}

.typing-content {
  flex: 1;
  max-width: 70%;
}

.typing-bubble {
  background: #f8f9fa;
  padding: 12px 16px;
  border-radius: 18px;
  border-bottom-left-radius: 6px;
}

.typing-dots {
  display: flex;
  gap: 4px;
}

.typing-dots span {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: #6c757d;
  animation: typing 1.4s infinite;
}

.typing-dots span:nth-child(2) {
  animation-delay: 0.2s;
}

.typing-dots span:nth-child(3) {
  animation-delay: 0.4s;
}

@keyframes typing {
  0%, 60%, 100% {
    transform: translateY(0);
    opacity: 0.4;
  }
  30% {
    transform: translateY(-10px);
    opacity: 1;
  }
}

@media (max-width: 768px) {
  .chat-header {
    padding: 12px 16px;
  }
  
  .app-title {
    font-size: 1.3rem;
  }
  
  .suggestion-buttons {
    gap: 10px;
  }
  
  .suggestion-btn {
    padding: 10px 16px;
    font-size: 14px;
  }
}
</style>